package com.japp.tools.common;

import java.beans.PropertyDescriptor;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import net.sf.json.JSONArray;
import com.japp.base.BaseBean;
import com.japp.sys.bean.SelectBean;

public class Common {

	/**
	 * 格式化SELECT
	 * @param list
	 * @return Json类型的String
	 * @throws Exception
	 */
	public static String formtSelectToJson (List<SelectBean> list) throws Exception{
		String json_str;
		if(list!=null&&list.size()>0){
				json_str = ("{\"list\":"+JSONArray.fromObject(list).toString()+"}").replace(",\"callbacks\":[{}]", "");
		}else{
			json_str = "{\"list\":[{\"value\":\"-1\",\"key\":\"无\"}]}";
		}
		return json_str;
	}
	/**
	 * 转换小数点
	 * @param numbers
	 * @return
	 */
	public static String DoubleFormatTwo(double numbers){
		DecimalFormat df = new DecimalFormat("#.00");
		return df.format(numbers);
	}
	/**
	 * 类型转换为加,号的数字类型
	 * @param numbers
	 * @return
	 */
	public static String DoubleFormatDigits(double numbers){
		NumberFormat nf = NumberFormat.getCurrencyInstance();
		nf.setMaximumFractionDigits(2);
		return nf.format(numbers);
	}
	/**
	 * 相应的时间减
	 * @return
	 */
	public static String getThisDateYMD(String obj,String obj1,String obj2,int obj3){
		 GregorianCalendar gc  = new GregorianCalendar();
		 if(obj!=null&&!"".equals(obj.trim())){
			SimpleDateFormat sd = new SimpleDateFormat(obj1);
			try {
				gc.setTime(sd.parse(obj));
			} catch (ParseException e) {
				e.printStackTrace();
			}
			if("Y".equals(obj2)){
				gc.add(1, obj3);
			}else if("M".equals(obj2)){
				gc.add(2, obj3);
			}else if("IW".equals(obj2)){
				gc.add(3, obj3);
			}else if("D".equals(obj2)){
				gc.add(5, obj3);
			}
			return sd.format(gc.getTime());
		 }
		return "";
	}

	public static String getThisDateJdStart(String obj,String date){
		if("1".equals(obj)){
			obj = "9999-01-01";
		}else if("2".equals(obj)){
			obj = "9999-04-01";
		}else if("3".equals(obj)){
			obj = "9999-07-01";
		}else if("4".equals(obj)){
			obj = "9999-10-01";
		}else{
			obj = date;
		}
		return obj;
	}
	/**
	 * 获取半年
	 * @param obj
	 * @return
	 */
	public static String getThisDateYear1(String obj){
		 Calendar calendar = Calendar.getInstance();
		 if(obj!=null&&!"".equals(obj.trim())){
			SimpleDateFormat sd = new SimpleDateFormat((obj.length()==4?"yyyy":"yyyy-MM"));
			try {
				calendar.setTime(sd.parse(obj));
			} catch (ParseException e) {
				e.printStackTrace();
			}
		 }
		 return ((calendar.get(Calendar.MONTH)+1)<7?"1":"2");
	}
	
	/**
	 * 将String 转换为DOUBLE
	 * @param str
	 * @return
	 */
	public static Double FormtDoubleByString(String str){
		return Double.valueOf(str);
	}
	/**
	 * 将String 转换为INTEGER
	 * @param str
	 * @return
	 */
	public static Integer FormtIntByString(String str){
		return Integer.valueOf(str);
	}
	/**
	 * 获取当前事件
	 * @return
	 */
	public static String getThisDate(){
		Calendar c = Calendar.getInstance();
		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
		return sd.format(c.getTime());
	}
	/**
	 * 获取当前周
	 * @return
	 */
	public static int getThisDateWEEK(String obj){
		 Calendar calendar = Calendar.getInstance();
		 if(obj!=null&&!"".equals(obj.trim())){
			SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
			try {
				calendar.setTime(sd.parse(obj));
			} catch (ParseException e) {
				e.printStackTrace();
			}
		 }
	     return calendar.get(Calendar.WEEK_OF_YEAR);
	}
    public static Workbook getWorkbook(String fileName, File theFile) {
        InputStream is = null;
        Workbook wb = null;
        try {
            is = new FileInputStream(theFile);
            if (fileName.toLowerCase().endsWith("xls")) {
                wb = new HSSFWorkbook(is);
            }
            if (fileName.toLowerCase().endsWith("xlsx")) {
                wb = new XSSFWorkbook(is);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return wb;
    }
    public List<BaseBean> mapperOfExecl(String fileName, File theFile) {
        int rows = 0; // 表单行数
        Sheet sh = null; // 表单对象/工作表
        int shCont = 0; // 一个工作博有多少张工作表
        List<BaseBean> shList = new ArrayList<BaseBean>();
        try {
            Workbook wb = Common.getWorkbook(fileName, theFile);// 得到工作薄对象，直接调用getWorkBook();
            shCont = wb.getNumberOfSheets();
            for (int x = 0; x < shCont; x++) {// 循环所有表
                sh = wb.getSheetAt(x);
                if (sh == null) {
                    continue;
                }
                rows = sh.getPhysicalNumberOfRows();
                for (int y = 1; y < rows; y++) {// 循环所有行
                    Row xr = sh.getRow(y);
                    if (xr == null) {
                        continue;
                    }
                    BaseBean sd = this.doBean(xr);// 调用doBean(Row
                    // xr);把一行数据封装成一个具体对象,此方法要自己实现
                    shList.add(sd);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return shList;
    }
	private BaseBean doBean(Row xr) {
		// TODO Auto-generated method stub
		return null;
	}
	/**
	 * 	public StandardBean doBean(Row xr) {
		Informers info=new Informers();
		String mark;
	    Integer clueNum;
	    Integer caseNum;
	    String marks=xr.getCell(0).getStringCellValue();
	    mark=marks+"";
	    clueNum=(int)(xr.getCell(1).getNumericCellValue());
	    caseNum=(int)(xr.getCell(1).getNumericCellValue());
	    info.setMark(mark);
	    info.setClueNum(clueNum);
	    info.setCaseNum(caseNum);
		return info;
	}
	 */
	/**
	 * 动态插入
	 * 
	 * @param obj
	 * @param rs
	 * @return Jion
	 */
	public static Object getObjView(Object obj, ResultSet rs) {
		if (obj != null) {
			try {
				// obj = obj.getClass().newInstance(); // 重新实例化该类
				Class<?> class1 = obj.getClass();
				PropertyDescriptor pd = null; // JavaBean
				String varName = ""; // 属性名称
				Method method = null; // 获取单个属性方法
				Class<?> varType = null; // 属性类型
				Field field = null;
				ResultSetMetaData rm = rs.getMetaData(); // 关于 ResultSet
				// 对象中列的类型和属性信息的对象
				int len = rm.getColumnCount() + 1;
				for (int i = 1; i < len; i++) {
					varName = rm.getColumnName(i).toLowerCase(
							Locale.getDefault());
					// 获取Java Bean
					field = class1.getDeclaredField(varName);
					if (field != null) {
						pd = new PropertyDescriptor(varName, class1);
						// 获取读写方法
						method = pd.getWriteMethod();
						varType = field.getType();
						// String 类型
						if (String.class == varType) {
							method.invoke(obj, rs.getString(i));
							// integer类型
						} else if (Integer.class == varType) {
							method.invoke(obj, rs.getInt(i));
							// folat类型
						} else if (Float.class == varType) {
							method.invoke(obj, rs.getFloat(i));
						} else if (varType == Double.class
								|| "double".equals(varType.toString())) {
							method.invoke(obj, rs.getDouble(i));
						} else if (varType == BigDecimal.class
								|| "BigDecimal".equals(varType.toString())) {
							method.invoke(obj, rs.getBigDecimal(i));
						} else {
							continue;
						}
					} else {
						JappLog.log.debug(class1.getName() + "实体类中不存在名称为:"
								+ varName + "的属性");
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return obj;
	}
	/**
	 * 动态插入
	 * 
	 * @param obj
	 * @param rs
	 * @return Jion
	 */
	public static Object getObjView(Object obj, ResultSet rs,boolean bool) {
		if (obj != null) {
			try {
				if(bool){
					obj = obj.getClass().newInstance(); // 重新实例化该类
				}
				Class<?> class1 = obj.getClass();
				PropertyDescriptor pd = null; // JavaBean
				String varName = ""; // 属性名称
				Method method = null; // 获取单个属性方法
				Class<?> varType = null; // 属性类型
				Field field = null;
				ResultSetMetaData rm = rs.getMetaData(); // 关于 ResultSet
				// 对象中列的类型和属性信息的对象
				int len = rm.getColumnCount() + 1;
				for (int i = 1; i < len; i++) {
					varName = rm.getColumnName(i).toLowerCase(
							Locale.getDefault());
					// 获取Java Bean
					field = class1.getDeclaredField(varName);
					if (field != null) {
						pd = new PropertyDescriptor(varName, class1);
						// 获取读写方法
						method = pd.getWriteMethod();
						varType = field.getType();
						// String 类型
						if (String.class == varType) {
							method.invoke(obj, rs.getString(i));
							// integer类型
						} else if (Integer.class == varType) {
							method.invoke(obj, rs.getInt(i));
							// folat类型
						} else if (Float.class == varType) {
							method.invoke(obj, rs.getFloat(i));
						} else if (varType == Double.class
								|| "double".equals(varType.toString())) {
							method.invoke(obj, rs.getDouble(i));
						} else {
							continue;
						}
					} else {
						JappLog.log.debug(class1.getName() + "实体类中不存在名称为:"
								+ varName + "的属性");
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return obj;
	}

	public static String checkDateByType(int type){
		SimpleDateFormat sd = null;
		Calendar calendar = new GregorianCalendar();  
		//calendar.setTime(new Date());
		if(2==type){
			sd = new SimpleDateFormat("yyyy-MM-dd");
			calendar.set(Calendar.WEEK_OF_YEAR, calendar.get(Calendar.WEEK_OF_YEAR)+1);
		}else if(3==type){
			sd = new SimpleDateFormat("yyyy-MM");
			calendar.set(Calendar.WEEK_OF_MONTH, calendar.get(Calendar.WEEK_OF_MONTH)+1);
		}else if(4==type){
			sd = new SimpleDateFormat("yyyy-MM");
			int currentMonth = calendar.get(Calendar.MONTH)+2;
			int jd = Common.getJdByMonth(currentMonth);
			//getThisDateJdStart
			String str = "{\"list\":[";
			String jdname = "";
			for (int i=1;i<=jd;i++){
				if(i==1)jdname="第一季度";
				if(i==2)jdname="第二季度";
				if(i==3)jdname="第三季度";
				if(i==4)jdname="第四季度";
				str+="{\"value\":\""+Common.getThisDateJdStart(String.valueOf(i), "").toString().substring(4,7)+"\",\"key\":\""+jdname+"\"},";
			}
			str = str.substring(0,str.length()-1);
			str+="]}";
			return str;
		}else if(5==type){
			int currentMonth = calendar.get(Calendar.MONTH)+2;
			int nd = 0;
			if(currentMonth<=6){
				nd = 1;
			}else{
				nd = 2;
			}
			String str = "{\"list\":[";
			String jdname = "";
			for (int i=1;i<=nd;i++){
				if(i==1)jdname="上半年";
				if(i==2)jdname="下班年";
				str+="{\"value\":\""+(i==1?"-01-01":"-07-01")+"\",\"key\":\""+jdname+"\"},";
			}
			str = str.substring(0,str.length()-1);
			str+="]}";
			return str;
		}else if(6==type){
			sd = new SimpleDateFormat("yyyy-MM");
			calendar.set(Calendar.WEEK_OF_MONTH, calendar.get(Calendar.WEEK_OF_MONTH)+1);
		}else if(7==type){
			sd = new SimpleDateFormat("yyyy");
			calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH)+1);
		}
		return sd.format(calendar.getTime());
	}
	private static int getJdByMonth(int currentMonth){
		 int i = 0;
		 if (currentMonth >= 1 && currentMonth <= 3){
               i = 1;//第一季度
		 }else if (currentMonth >= 4 && currentMonth <= 6){
               i = 2;//第一季度
		 } else if (currentMonth >= 7 && currentMonth <= 9){
               i = 3;//第一季度
		}else if (currentMonth >= 10 && currentMonth <= 12){
           		i = 4;//第一季度
       }
		 return i;
	}
	public static void main(String[] args) {
		System.out.println(Common.checkDateByType(3));
	}
}
